package cn.yh.register.order.service.impl;

import cn.yh.register.client.hosp.HospitalFeignClient;
import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.helper.HttpRequestHelper;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.enums.OrderStatusEnum;
import cn.yh.register.enums.PaymentStatusEnum;
import cn.yh.register.model.order.OrderInfo;
import cn.yh.register.model.order.PaymentInfo;
import cn.yh.register.order.mapper.PaymentInfoMapper;
import cn.yh.register.order.service.OrderService;
import cn.yh.register.order.service.PaymentInfoService;
import cn.yh.register.vo.order.SignInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Transactional(rollbackFor = Exception.class)
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    OrderService orderService;
    @Autowired
    HospitalFeignClient hospitalFeignClient;

    /**
     * 保存交易记录
     * @param orderInfo   交易记录对象
     * @param paymentType 交易类型 （1:支付宝  2:微信）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 先查询是否有支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderInfo.getId())
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (paymentInfo != null) {
            return;
        }
        // 不存在，保存支付记录
        paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        // 支付状态
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        baseMapper.insert(paymentInfo);
    }

    /**
     * 支付成功 更新支付记录 & 更新订单状态  & 对接医院系统更新订单
     * @param outTradeNo  订单号
     * @param paymentType 支付类型
     * @param resultMap   微信响应的数据
     */
    @Override
    public void paySuccess(String outTradeNo, Integer paymentType, Map<String, String> resultMap) {
        // 查询支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, outTradeNo)
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (paymentInfo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        // 支付成功 更新支付记录
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus()); // 2：已支付
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
        baseMapper.updateById(paymentInfo);
        // & 更新订单状态
        OrderInfo orderInfo = orderService.getOrderInfo(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus()); // 1.已支付
        boolean b = orderService.updateById(orderInfo);

        // 获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (signInfoVo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        // & 对接医院系统更新订单
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("hosRecordId", orderInfo.getHosRecordId());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        paramMap.put("sign", HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey()));
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if (200 != jsonObject.getInteger("code")) {
            throw new RegisterException(jsonObject.getString("message"), jsonObject.getInteger("code"));
        }
    }

    /**
     * 获取支付记录
     * @param orderId     订单Id
     * @param paymentType 支付类型
     * @return 支付记录
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {

        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderId)
                .eq(PaymentInfo::getPaymentType, paymentType));
        return paymentInfo;
    }

}
